import {history, post, message, get} from '@/utils/utils'

const merchantTrade = {
  namespaced: true,
  state: {
    currentSummary: {},
    tradeList: [],
    pageNum: 1,
    hasData: true
  },

  mutations: {
    save(state, { list, pageNum }) {
      if (state.pageNum === 1) {
        state.tradeList = list
      } else {
        state.tradeList = state.tradeList.concat(list)
      }
      state.pageNum = pageNum
    },
    addCurrentSummary(state, currentSummary) {
      state.currentSummary = currentSummary
    },
    changeState(state, {field, payload}) {
      if (Object.prototype.toString.call(payload) === '[object Object]') {
        state[field] = { ...state[field], ...payload }
      } else {
        state[field] = payload
      }
    }
  },

  actions: {
    getTradeList({ commit, dispatch }, pageNum = 1) {
      get({api: '/agt/agentmonthsummary/getSummaryPage',
        data: {
          current: pageNum
        },
        success: ({data}) => {
          const list = data.records
          const {pages} = data
          if (pages === pageNum || pages === 0) commit('changeState', {field: 'hasData', payload: false})
          commit('save', {list, pageNum: data.current})
        }})
    },
    getCurrentSummary({commit, state}) {
      get({api: '/agt/agentmonthsummary/getAgentMonthSummaryWithAgentNo',
        success: ({data}) => {
          commit('addCurrentSummary', data)
        }})
    }
  }
}

export default merchantTrade
